import React from 'react';
import {connect} from 'react-redux';
import {View, Text, TextInput, TouchableOpacity, Image, KeyboardAvoidingView, Platform} from  'react-native';
import BaseNaviLayout from '../../component/BaseNaviLayout';
import styles from './styles';
import {getCodeAction, resetCodeAction, registerAction, resetPwdAction} from './actions';
import {toast} from  '../../utils/NativeUtil';
import CLNavigatorHeader from '../../component/CLNavigatorHeader';
import {naviPush, naviReset,naviBack, gotoView} from '../../navigatorApp/actions';
import themeconfig from '../../config/theme';

class register extends React.Component {


    static navigationOptions = ({navigation, screenProps}) => {
        const {params = {}} = navigation.state;
        let temp = '';
        if (params.type == 'register') {
            temp = '注册'
        } else {
            temp = '忘记密码'
        }
        let header = (<CLNavigatorHeader navigation={navigation} title={temp}/>);
        return {header}
    };

    constructor(props) {
        super(props);
        this.codeTime = 120;
        this.timer = null;
        this.codeEnable = true;
        this.state = {
            loginId: '',
            password: '',
            // passwordconfirm: '',
            code: '',
            codeValue: '获取验证码',
        };
        this.btnvalue = "";
        this.type = props.navigation.state.params.type;
        if (this.type == "register") {
            btnvalue = "注册";
        } else {
            btnvalue = "重置密码";
        }
    }

    //点击获取验证码
    getCodeClick = () => {
        let self = this;
        if (this.state.loginId.length == 0) {
            toast('手机号码不能为空');
            return;
        }

        if (!this.codeEnable) {
            return;
        }


        //获取验证码
        if (this.type == 'register') {
            this.props.getCode(this.state.loginId, function () {
                var time = 0;
                self.timer = setInterval(function () {
                    var timenow = self.codeTime - time;
                    if (timenow > 0) {
                        self.setState({codeValue: timenow + '秒'});
                        self.codeEnable = false;
                    } else {
                        self.timer && clearInterval(self.timer);
                        self.codeEnable = true;
                        self.setState({codeValue: '获取验证码'});
                        time = 0;
                    }
                    time++;
                }, 1000);
            });
        } else {
            this.props.resetCode(this.state.loginId, function (res) {
                var time = 0;
                self.timer = setInterval(function () {
                    var timenow = self.codeTime - time;
                    if (timenow > 0) {
                        self.setState({codeValue: timenow + '秒'});
                        self.codeEnable = false;
                    } else {
                        self.timer && clearInterval(self.timer);
                        self.codeEnable = true;
                        self.setState({codeValue: '获取验证码'});
                        time = 0;
                    }
                    time++;
                }, 1000);
            });
        }
    };

    loginTxtChange = (txt) => {
        this.setState({
            loginId: txt
        })
    };

    passwordTxtChange = (txt) => {
        this.setState({
            password: txt
        })
    };

    codeTxtChange = (txt) => {
        this.setState({
            code: txt
        })
    };

    componentWillUnmount() {
        this.timer && clearInterval(this.timer);
    }

    registerClick = () => {
        var self = this;

        if (this.state.loginId.length == 0) {
            toast('手机号码不能为空');
            return;
        }

        if (this.state.password.length == 0) {
            toast('密码不能为空');
            return;
        }

        // if (this.state.password != this.state.passwordconfirm) {
        //     toast('两次输入密码不一致');
        //     return;
        // }

        if (this.state.code.length == 0) {
            toast('验证码不能为空');
            return;
        }

        if (this.type == 'register') {
            this.props.registerUser(this.state.loginId, this.state.password, this.state.code, function () {
                //跳到首页
                toast('注册成功');
                self.props.naviBack();
                self.props.gotoView('home');
            });
        } else {
            this.props.resetPwd(this.state.loginId, this.state.password, this.state.code, function () {
                toast('修改成功');
                const params = {
                    type: 'login',
                    title: ''
                };
                self.props.naviPush("Home", params)
            });
        }
    };

    render = () => {
        return (
            <View style={{
                flex: 1,
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: '#ebedea'
            }}>
                <KeyboardAvoidingView behavior={(Platform.OS === 'ios') ? 'position' : ''}
                                      keyboardVerticalOffset={ (Platform.OS === 'ios') ? 64 : 0 }>
                    <View style={{flexDirection: 'column', margin: 10}}>
                        <View style={styles.inputItem}>
                            <Image source={require('../../image/img_user.png')} style={{width: 23, height: 23}}/>
                            <TextInput style={styles.inputStyle}
                                       color={themeconfig.maincolor}
                                       fontSize={18}
                                       multiline={false}
                                       underlineColorAndroid={'transparent'}
                                       value={this.state.loginId}
                                       onChangeText={this.loginTxtChange}
                                       placeholder={"请输入手机号码"}
                                       keyboardType="numeric"/>
                        </View>
                        <View style={styles.inputLine}/>
                        <View style={styles.inputItem}>
                            <Image source={require('../../image/img_code.png')} style={{width: 23, height: 23}}/>
                            <TextInput style={styles.inputStyle}
                                       underlineColorAndroid={'transparent'}
                                       color={themeconfig.maincolor}
                                       fontSize={18}
                                       value={this.state.code}
                                       onChangeText={this.codeTxtChange}
                                       placeholder={"请输入验证码"}
                                       keyboardType="numeric"/>
                            <TouchableOpacity onPress={this.getCodeClick}>
                                <View style={{
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    flexDirection: 'row',
                                    backgroundColor: '#aaedf0',
                                    borderRadius: 20,
                                    height: 30,
                                    width: 80,
                                    paddingTop: 12,
                                    paddingBottom: 12
                                }}>
                                    <Text style={styles.getCodeStyle}>{this.state.codeValue}</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.inputLine}/>
                        <View style={styles.inputItem}>
                            <Image source={require('../../image/img_password.png')} style={{width: 23, height: 23}}/>
                            <TextInput style={styles.inputStyle}
                                       color={themeconfig.maincolor}
                                       fontSize={18}
                                       value={this.state.password}
                                       placeholder={"请输入密码"}
                                       secureTextEntry={true}
                                       underlineColorAndroid={'transparent'}
                                       onChangeText={this.passwordTxtChange}
                                       multiline={false}/>
                        </View>
                        <View style={styles.inputLine}/>
                        {/* <View style={styles.inputItem}>
                            <Image source={require('../../image/img_password.png')} style={{width: 23, height: 23}}/>
                            <TextInput style={styles.inputStyle}
                                       color={themeconfig.maincolor}
                                       fontSize={18}
                                       value={this.state.passwordconfirm}
                                       placeholder={"请确认密码"}
                                       secureTextEntry={true}
                                       underlineColorAndroid={'transparent'}
                                       onChangeText={(text) => this.setState({passwordconfirm: text})}
                                       multiline={false}/>
                        </View>
                        <View style={styles.inputLine}/> */}
                        <View style={{width: 0, height: 39}}/>
                        <TouchableOpacity onPress={this.registerClick}>
                            <View style={styles.btnViewStyle}>
                                <Text style={styles.loginBtnStyle}>{btnvalue}</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </KeyboardAvoidingView>
            </View>
        );
    }


}

const mapStateToProps = state => ({});

const mapDispatchToProps = (dispatch) => {
    return {
        getCode: (phone, success) => {
            dispatch(getCodeAction(phone, success))
        },

        resetCode: (phone, success) => {
            dispatch(resetCodeAction(phone, success))
        },

        registerUser: (phone, pwd, code, success) => {
            dispatch(registerAction(phone, pwd, code, success));
        },

        resetPwd: (phone, pwd, code, success) => {
            dispatch(resetPwdAction(phone, pwd, code, success));
        },
        naviReset: (value) => {
            dispatch(naviReset(value))
        },
        gotoView: (value) => {
            dispatch(gotoView(value))
        },
        naviPush: (routeName, params) => {
            dispatch(naviPush(routeName, params))
        },
        naviBack : (routeName) => {
            dispatch(naviBack(routeName))
        }
    }
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(register);


